import request from "../../../request.js"
import cfg from "../../../config.js"

let page_type = {
    open: async function (page_info) {
        let page_html_id = page_info.page_html_id;
        let property = page_info.property;
        let ext_js = page_info.ext_js;
        let page_id = page_info.page_id;
        let rights = page_info.rights;
        let params = page_info.params;
        let diagram_xml = property.diagram;
        let form_id = property.form_id;
        $("#" + page_html_id).addClass("process-builder-page row");
        $("#" + page_html_id).html('\
        <div class="col-md-8 col-sm-12 col-xs-12" style="padding:0rem;">\
            <div class="bpmn-canvas view-part" style="height:650px;background:#fff;"></div>\
        </div>\
        <div class="col-md-4 col-sm-12 col-xs-12" style="padding-left:0.75rem;padding-right:0;">\
            <div class="config-part"></div>\
        </div>\
        <style>\
            .process-builder-page .config-part .amis-scope{padding:0.5rem}\
            .process-builder-page .config-part .amis-scope .antd-Panel{border-color:white;}\
            .process-builder-page .config-part .amis-scope .antd-Panel-body{padding:0;}\
            .process-builder-page .config-part .amis-scope .combo-configer>div>div>div>.antd-Combo-item{padding:0;border:0;}\
        </style>\
        <!-- BPMN -->\
        <link rel="stylesheet" href="bpmn-js/dist/assets/diagram-js.css">\
        <link rel="stylesheet" href="bpmn-js/dist/assets/bpmn-font/css/bpmn.css">\
        <script src="bpmn-js/dist/bpmn-modeler.production.min.js"></script>');

        var diagramUrl = 'bpmn-js/new.bpmn';
        // modeler instance
        var bpmnModeler = new BpmnJS({
            container: "#" + page_html_id + " .bpmn-canvas",
            keyboard: {
                bindTo: window
            }
        });
        /**
       * Save diagram contents and print them to the console.
       */
        async function exportDiagram() {
            try {
                var result = await bpmnModeler.saveXML({ format: true });
                alert('Diagram exported. Check the developer tools!');
                console.log('DIAGRAM', result.xml);
            } catch (err) {
                console.error('could not save BPMN 2.0 diagram', err);
            }
        }
        /**
         * Open diagram in our modeler instance.
         *
         * @param {String} bpmnXML diagram to display
         */
        async function openDiagram(bpmnXML) {

            // import diagram
            try {
                await bpmnModeler.importXML(bpmnXML);
                // access modeler components
                var canvas = bpmnModeler.get('canvas');
                var overlays = bpmnModeler.get('overlays');
                // zoom to fit full viewport
                canvas.zoom("fit-viewport", "auto");
            } catch (err) {
                console.error('could not import BPMN 2.0 diagram', err);
            }
        }
        // load external diagram file via AJAX and open it
        if (diagram_xml) {
            openDiagram(diagram_xml);
        }
        else {
            $.get(diagramUrl, openDiagram, 'text');
        }

        var eventBus = bpmnModeler.get('eventBus');

        // you may hook into any of the following events
        var events = [
            'element.click'
        ];

        events.forEach(function (event) {
            eventBus.on(event, function (e) {
                // e.element = the model element
                // e.gfx = the graphical element
                if (event == "element.click") {
                    //console.log(e.element.id, e.element.type);
                    let element_id = e.element.id;
                    refresh_config(element_id);
                    refresh_config_panel();
                }
            });
        });

        let def_id = property.id;
        let def_name = property.name;
        let config = property.config ? JSON.parse(property.config) : undefined;
        let config_amisScoped;
        let amis = amisRequire('amis/embed');
        let bpm_process_design_configer; //_configer
        //////////////////配置面板//////////////////
        let refresh_config_panel = function () {
            let amisJSON = {
                "type": "page",
                "name": "config-page",
                "data": {
                    "api_server": cfg.api_server
                },
                "body": [
                    {
                        "type": "tabs",
                        "mode": "normal",
                        "className": "config-tabs",
                        "toolbar": [
                            {
                                "type": "button",
                                "label": "保存",
                                "className": "save-config",
                                "icon": "fa fa-save",
                                "onClick": async (a, b) => {
                                    let path = "bpm/design/save";
                                    var result = await bpmnModeler.saveXML({ format: true });
                                    let diagram_xml = result.xml;
                                    let process_config = config_amisScoped.getComponentByName("config-page.process_config_form").props.data;
                                    process_config.current_id = "Process_1";
                                    request(path, { id: def_id, name: def_name, diagram_xml: diagram_xml, process_config: process_config }, function (result) {
                                        alert("保存成功！");
                                    })
                                }
                            },
                            {
                                "type": "button",
                                "label": "保存&发布",
                                "className": "save-config",
                                "level": "primary",
                                "onClick": async (a, b) => {
                                    let path = "bpm/design/savepublish";
                                    var result = await bpmnModeler.saveXML({ format: true });
                                    let diagram_xml = result.xml;
                                    let process_config = config_amisScoped.getComponentByName("config-page.process_config_form").props.data;
                                    process_config.current_id = "Process_1";
                                    request(path, { id: def_id, name: def_name, diagram_xml: diagram_xml, process_config: process_config }, function (result) {
                                        alert("保存&发布成功！");
                                    })
                                }
                            }
                        ],
                        "tabs": [
                            {
                                "title": "流程配置",
                                "tab":
                                {
                                    "type": "form",
                                    "name": "process_config_form",
                                    "title": "",
                                    "submitText": "",
                                    "multiple": true,
                                    "data": {
                                        "current_id": 0,
                                        "user_tasks": [],
                                        "form_fields": [],
                                        "condition_fields": [],
                                        ...config.process_config
                                    },
                                    "controls": [
                                        ...bpm_process_design_configer.controls,
                                        {
                                            "type": "divider"
                                        },
                                        {
                                            "type": "fieldSet",
                                            "title": "JSON",
                                            "collapsable": true,
                                            "collapsed": true,
                                            "body": [
                                                {
                                                    "type": "static",
                                                    "tpl": "<pre>${configer|json}</pre>"
                                                }
                                            ]
                                        }
                                    ]
                                }

                            }
                        ]
                    }
                ]
            }
            let wrapperid = page_html_id + "_config_wrapper_" + Math.random().toString().split(".")[1];
            $("#" + page_html_id + " .config-part").html("<div id='" + wrapperid + "'></div>")

            config_amisScoped = amis.embed(
                '#' + page_html_id + " .config-part #" + wrapperid, amisJSON, {},
                {
                    theme: 'antd'
                }
            );

        }

        let refresh_config = function (element_id) {
            let data = config_amisScoped.getComponentByName("config-page.process_config_form").props.data;
            data.current_id = element_id;
            let rootElements = bpmnModeler.getDefinitions().rootElements;
            let user_tasks = [];
            //新的加到配置里
            for (let rootElement of rootElements) {
                if (!data.configer) {
                    data.configer = [];
                }
                let find = data.configer.filter(c => c.id == rootElement.id);
                if (find.length == 0) {
                    data.configer.push({
                        "type": rootElement.$type,
                        "id": rootElement.id,
                        "name": rootElement.name
                    })
                }
                else {
                    find[0].type = rootElement.$type;
                    find[0].name = rootElement.name;
                }
                let flowElements = rootElement.flowElements;
                for (let flowElement of flowElements) {
                    let find = data.configer.filter(c => c.id == flowElement.id);
                    if (find.length == 0) {
                        data.configer.push({
                            "type": flowElement.$type,
                            "id": flowElement.id,
                            "name": flowElement.name
                        })
                    }
                    else {
                        find[0].type = flowElement.$type;
                        find[0].name = flowElement.name;
                    }
                    //user_tasks
                    if (flowElement.$type == "bpmn:UserTask") {
                        user_tasks.push({
                            value: flowElement.id,
                            label: flowElement.name + " (" + flowElement.id + ")"
                        })
                        //表单权限刷新
                        let element = data.configer.filter(c => c.id == flowElement.id)[0];
                        if (!element.form_fields_rights) {
                            element.form_fields_rights = [];
                        }
                        let rights = [];
                        for (let f of form_fields) {
                            let find = element.form_fields_rights.filter(r => r.name == f.value);
                            if (find.length > 0) {
                                rights.push(find[0])
                            }
                            else {
                                rights.push({
                                    label: f.label,
                                    name: f.value,
                                    read: true,
                                    edit: true,
                                    required: false
                                })
                            }
                        }
                        element.form_fields_rights = rights;
                    }
                }
            }
            //删掉的同时清配置
            for (var i = data.configer.length - 1; i >= 0; i--) {
                let config = data.configer[i];
                let is_find = false;
                for (let rootElement of rootElements) {
                    if (rootElement.id == config.id) {
                        is_find = true;
                    }
                    let flowElements = rootElement.flowElements;
                    if (flowElements.some(e => e.id == config.id)) {
                        is_find = true;
                    }
                }
                if (!is_find) {
                    data.configer.splice(i, 1);
                }
            }
            data.user_tasks = user_tasks;
            data.form_fields = form_fields;
            data.condition_fields = condition_fields;
            config.process_config = data;
        }

        let form_fields = [];
        let condition_fields = [{
            "label": "审批结果",
            "type": "select",
            "name": "approve_result",
            "options": [
                {
                    "label": "同意",
                    "value": "同意"
                },
                {
                    "label": "不同意",
                    "value": "不同意"
                }
            ]
        }];
        let path = "page/info";
        request(path, { "id": form_id }, function (data) {
            if (data.length == 0) {
                alert("未获取到表单数据");
            }
            let columns = data.property.page.controls;
            let condition_fields_form_fields = {
                "label": "表单字段",
                "children": []
            }
            for (let c of columns) {
                form_fields.push({
                    label: c.name + " (" + c.field_name + ")",
                    value: c.field_name
                });
                condition_fields_form_fields.children.push({
                    "label": c.name,
                    "type": "text",
                    "name": c.field_name
                })
            }
            condition_fields.push(condition_fields_form_fields);
            path = "configer/getbyname",
                request(path, { "name": "bpm_process_design" }, function (data) {
                    bpm_process_design_configer = data;
                    refresh_config_panel();
                })
        })

    }
}

export default page_type;